package com.yz.forlogin.system.service;

import com.yz.forlogin.security.entity.Admin;
import com.yz.forlogin.security.entity.Customer;
import com.yz.forlogin.security.utils.IdWorker;
import com.yz.forlogin.system.exception.UserNameAlreadyExistException;
import com.yz.forlogin.system.repository.AdminRepository;
import com.yz.forlogin.system.repository.UserRepository;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.Optional;

/**
 * @author 钰杰
 */
@Service
public class UserService {

    private final UserRepository userRepository;

    @Autowired
    private  AdminRepository adminRepository;

    private final BCryptPasswordEncoder bCryptPasswordEncoder;

    public UserService(UserRepository userRepository, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userRepository = userRepository;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    public void saveUser(Map<String, String> registerUser) {
        Optional<Customer> optionalUser = Optional.ofNullable(userRepository.findByUsername(registerUser.get("username")));
        if (optionalUser.isPresent()) {
            throw new UserNameAlreadyExistException("User name already exist!Please choose another user name.");
        }
        Customer user = new Customer();
        user.setUsername(registerUser.get("username"));
        user.setPassword(bCryptPasswordEncoder.encode(registerUser.get("password")));
        IdWorker idWorker = new IdWorker();
        long l = idWorker.nextId();
        user.setAppid(l+"");
        user.setBalance(0.00);
        user.setDstatus(1);
        user.setUserType(Integer.parseInt(registerUser.get("usertype")));
        userRepository.save(user);
    }

    //用户登录
    public Object findUserByUserName(String name) {
        Customer user = userRepository.findByUsername(name);
        if (StringUtils.isEmpty(user)) {
            Admin admin = adminRepository.findByUsername(name).get();
            return admin;
        }
        return user;
    }


    public Customer getUserInfoByUsername(String username) {
        return userRepository.getUserInfoByUsername(username);
    }

    public void updatelastLogin(Integer id) {
        userRepository.updatelastLogin(id);
    }

    public void saveAdmin(Map<String, String> map) {

        Admin admin = new Admin();
        admin.setDstatus(1);
        admin.setPassword(bCryptPasswordEncoder.encode(map.get("password")));
        admin.setRole(map.get("role").toUpperCase());
        admin.setUsername(map.get("username"));
        adminRepository.save(admin);
    }
}
